/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.dbswitch.service.impl.metadata;

import com.alibaba.druid.pool.DruidDataSource;
import com.je.common.base.spring.SpringContextHolder;
import com.je.meta.model.database.type.ProductTypeEnum;
import com.je.meta.service.dbswitch.eneity.DatabaseConnectionEntity;
import com.je.meta.service.dbswitch.excption.DbswitchException;
import com.je.meta.service.dbswitch.response.ResultCode;
import com.je.meta.service.dbswitch.service.DbConnectionService;
import com.je.meta.service.dbswitch.type.SupportDbTypeEnum;
import com.je.meta.service.dbswitch.service.IMetaDataByJdbcService;
import com.je.meta.util.database.JDBCURL;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;

@Service
public class DbConnectionServiceImpl implements DbConnectionService {

    public IMetaDataByJdbcService getMetaDataCoreService(DatabaseConnectionEntity dbConn) {
        IMetaDataByJdbcService metaDataService = new MetaDataByJdbcServiceImpl(getType(dbConn));
        return metaDataService;
    }

    private ProductTypeEnum getType(DatabaseConnectionEntity dbConn) {
        String typeName = dbConn.getType().getName().toUpperCase();
        SupportDbTypeEnum supportDbType = SupportDbTypeEnum.valueOf(typeName);
        if (supportDbType.hasAddress()) {
            for (String pattern : supportDbType.getUrl()) {
                final Matcher matcher = JDBCURL.getPattern(pattern).matcher(dbConn.getUrl());
                if (!matcher.matches()) {
                    if (1 == supportDbType.getUrl().length) {
                        throw new DbswitchException(ResultCode.ERROR_CANNOT_CONNECT_REMOTE, dbConn.getName());
                    } else {
                        continue;
                    }
                }

                String host = matcher.group("host");
                String port = matcher.group("port");
                if (StringUtils.isBlank(port)) {
                    port = String.valueOf(supportDbType.getPort());
                }

                if (!JDBCURL.reachable(host, port)) {
                    throw new DbswitchException(ResultCode.ERROR_CANNOT_CONNECT_REMOTE, dbConn.getName());
                }
            }
        }
        ProductTypeEnum prd = ProductTypeEnum.valueOf(dbConn.getType().getName().toUpperCase());
        return prd;
    }

    public DatabaseConnectionEntity getDatabaseConnection() {
        DruidDataSource druidDataSource = SpringContextHolder.getBean("dataSource");
        DatabaseConnectionEntity databaseConnectionEntity = new DatabaseConnectionEntity();
        databaseConnectionEntity.setName(druidDataSource.getName());
        databaseConnectionEntity.setDriver(druidDataSource.getDriver().toString());
        databaseConnectionEntity.setType(SupportDbTypeEnum.getSupportDbTypeEnumByName(druidDataSource.getDbType()));
        databaseConnectionEntity.setUrl(druidDataSource.getUrl());
        databaseConnectionEntity.setUsername(druidDataSource.getUsername());
        databaseConnectionEntity.setPassword(druidDataSource.getPassword());
        return databaseConnectionEntity;
    }

}
